const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const amqp = require('amqplib/callback_api');
const log = require('./com/logConfig')
const rabbitMqService = require('./service/rabbitMqService.js')
//mongoose
const mongoose = require('mongoose')

var cors = require('koa2-cors');

//api
const noteController = require('./routes/noteController')
const studentController = require('./routes/studentController')
const getDocsController = require('./routes/getDocsController')
const fenceController = require('./routes/fenceController')
const processHistoryController = require('./routes/processHistoryController')
const travelRecordController = require('./routes/travelRecordController')

// 二、 连接数据库的服务  若是带账号密码的：'mongodb://root:123456@127.0.0.1:27017/dumall'
mongoose.set('useCreateIndex', true);

onerror(app)

app.use(bodyparser())
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

//允许跨域
app.use(cors({
  allowMethods: ['GET', 'POST'],
  allowHeaders: ['Content-Type', 'Accept'],
  origin: function (ctx) {
    return '*' // 本地环境
  }
}));
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(noteController.routes(), noteController.allowedMethods())
app.use(studentController.routes(), studentController.allowedMethods())
app.use(getDocsController.routes(), getDocsController.allowedMethods())
app.use(fenceController.routes(), fenceController.allowedMethods())
app.use(processHistoryController.routes(), processHistoryController.allowedMethods())
app.use(travelRecordController.routes(), travelRecordController.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});
//监听未捕获的异常 - 可防止一个异常导致进程堵死
process.on('uncaughtException', function (e) {
  log.error('全局异常');
  log.error(e);
});
//监听Promise没有被捕获的失败函数 - 可防止一个失败导致进程堵死
process.on('unhandledRejection',function(err,promise){
  log.error('全局异常');
  log.error(err);
});

//rabbitmq连接
try {
  amqp.connect({
    hostname: global.COM_CONFIG.rabbitmq.host,
    port: global.COM_CONFIG.rabbitmq.port,
    username: global.COM_CONFIG.rabbitmq.user,
    password: global.COM_CONFIG.rabbitmq.password
  }, function (error0, connection) {
    if (error0) {
      log.error("连接rabbitmq失败：", error0);
      return;
    }
    //组装消息提供者
    rabbitMqService.writeSendQueue(connection);
    //组装消息消费者 - 处理各种队列的消息
    rabbitMqService.handleMessage(connection);
  });
} catch (e) {
  log.error(e);
}

//swagger文档地址：http://localhost:9012/swagger-ui/index.html
//在上线呢的时候要把public里面的index.html文件的拉取json的地址改成真正的地址，才能通过本项目访问接口文档
//并且编辑swagger.json里面的host: '127.0.0.1:9012'  basePath: / 字段  才能在线try it访问
//创建编辑swagger.json文件地址：http://localhost:9012/swagger-editor/index.html

module.exports = app











